#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Time   : 2022/9/7 19:23
# @Author : cjw
import json
from typing import Optional

import allure
import requests
from requests.models import Response
from loguru import logger

from api_wework.setting import TIMEOUT


class BaseApi:
    base_url: str = ''

    def request(self, data: dict) -> Response:
        """
        发送请求
        :param data: 请求的数据
        :return:
        """
        # 为了多协议支持，或者将来协议变更，或者将来方便切换不同的http库
        if 'url' in data:
            # 增加超时时间
            data.update(timeout=TIMEOUT)
            # 拼接请求地址
            data['url'] = self.base_url + data['url']
            return next(self._http_request(data))

    def _http_request(self, data: dict) -> Response:
        """
        发送http请求, 返回响应后，再关闭http连接
        :param data: 请求数据
        :return:
        """
        rsp: Optional[Response] = None
        try:
            with allure.step(msg := f'发送【{data.get("method")}】请求：{data.get("url")}'):
                logger.info(msg)
            with allure.step(f'请求参数：{data}'):
                logger.info(f'\n==================================== 请求参数 ===================================='
                            f'\n{json.dumps(data, indent=2, ensure_ascii=False)}')
            rsp = requests.request(**data)

            # 格式化缩进打印返回响应数据
            with allure.step(f'响应结果：{rsp.json()}'):
                logger.info(f'\n==================================== 响应结果 ===================================='
                            f'\n{json.dumps(rsp.json(), indent=2, ensure_ascii=False)}')
            yield rsp
        except Exception as e:
            with allure.step(msg := f'请求异常：{e}'):
                logger.info(msg)
            raise e
        finally:
            with allure.step(msg := f'关闭连接：{rsp.url}'):
                logger.info(msg)
            rsp.close()
